<template>
  <div class="app-container">
    <div class="header-wrap">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="120px">
        <el-form-item label="用户昵称" prop="inviteMobile">
          <el-input v-model="queryParams.nickName" placeholder="请输入用户昵称" clearable size="small" style="width: 240px" @keyup.enter.native="getUserList" />
        </el-form-item>
        <el-form-item label="用户类型" prop="type">
          <el-select style="width: 240px" v-model="queryParams.type" placeholder="请选择" clearable size="small">
            <el-option v-for="dict in userTypes" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="onSearchClick">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="f-r">
        <!-- <el-button type="success" icon="el-icon-plus" size="mini" @click="handleCreate">新建标签</el-button> -->
        <el-popover v-model="showAddTagView" placement="bottom" trigger="click" @hide="onTagPopoverHide">
          <el-form ref="addTagForm" :model="addTagForm">
            <div class="addTagTitle">标签名称</div>
            <el-form-item prop="tagName" :rules="[{ required: true, message: '标签不能为空', trigger: 'blur' }]">
              <el-input v-model="addTagForm.tagName" placeholder="请输入标签名称" clearable size="small" style="width: 240px" />
            </el-form-item>
            <div class="operationView addTagOperation">
              <el-button class="confirm" type="primary" @click="onConfirmAddTag">确 定</el-button>
              <el-button class="cancel" @click="onCancelAddTag">取 消</el-button>
            </div>
          </el-form>

          <el-button class="addTagBtn" type="success" size="mini" icon="el-icon-plus" slot="reference">新建标签</el-button>
        </el-popover>
      </div>
    </div>
    <div class="content">
      <div class="userList">
        <div class="listTitle">全部用户</div>
        <!-- @selection-change="handleSelectionChange" -->
        <el-table ref="multipleTable" :data="userData" tooltip-effect="dark" style="width: 100%" max-height="800" @select="onUserSelected" @select-all="onUserSelectedAll" :row-key="(row) => {return row.id}">
          <el-table-column class='check-all' type="selection" width="80" :reserve-selection="true" />
          <el-table-column>
            <template slot="header">
              <el-button v-if="!tagEditEnable" :disabled="selectedUsers.length === 0" size="mini" @click="handleTag">打标签</el-button>
              <!-- <el-button v-if="tagEditEnable" size="mini" @click="renameTag">重命名</el-button> -->
              <el-popover v-if="tagEditEnable" v-model="showRenamePopover" placement="bottom" trigger="click" @hide="onTagPopoverHide">
                <el-form ref="addTagForm" :model="addTagForm">
                  <div class="addTagTitle">标签名称</div>
                  <el-form-item prop="tagName" :rules="[{ required: true, message: '标签不能为空', trigger: 'blur' }]">
                    <el-input v-model="addTagForm.tagName" placeholder="请输入标签名称" clearable size="small" style="width: 240px" />
                  </el-form-item>
                  <div class="operationView addTagOperation">
                    <el-button class="confirm" type="primary" @click="onConfirmRenameTag">确 定</el-button>
                    <el-button class="cancel" @click="onCancelRenameTag">取 消</el-button>
                  </div>
                </el-form>
                <el-button class="addTagBtn" size="mini" slot="reference">重命名</el-button>
              </el-popover>

              <el-popover class="deleteTagPopover" v-if="tagEditEnable" v-model="showDeleteTagPopover" placement="bottom" trigger="click">
                <el-form ref="addTagForm" :model="addTagForm">
                  <div class="deleteHint">删除标签后，该标签下的所有用户将失去该标签属性。是否确定删除？</div>
                  <div class="operationView deleteTagOperation">
                    <el-button class="confirm" type="danger" @click="onConfirmDeleteTag">确 定</el-button>
                    <el-button class="cancel" @click="onCancelDeleteTag">取 消</el-button>
                  </div>
                </el-form>
                <el-button class="addTagBtn" size="mini" slot="reference">删除</el-button>
              </el-popover>

              <!-- <el-button v-if="tagEditEnable" size="mini" @click="deleteTag">删除</el-button> -->
            </template>
            <template slot-scope="scope">
              <div class="userItem">
                <img class="userItemImg" :src="scope.row.avatar != null ? (picturePath + '/' + scope.row.avatar) : defaultImage">
                <div>
                  <div class="username">{{scope.row.name}} <div v-if="scope.row.userType !== null" class="userTypeTag" :class="tagValues[scope.row.userType].privateStyle">{{tagValues[scope.row.userType].name}}</div>
                  </div>
                  <div class="tagsView">
                    <div class="tag" v-for="(tag, tagIndex) in scope.row.sign" v-bind:key="tagIndex">{{tag}}</div>
                    <el-popover v-model="scope.row.showSelector" placement="bottom" trigger="click" @show="onShowTagSelector(scope.row.sign)">
                      <div>
                        <div class="tagsSelector">
                          <div :class="{'tag': true, 'selectedTag': selectedTags.indexOf(selTag.sign) >= 0}" v-for="(selTag, selIndex) in tagsData" v-bind:key="selIndex" v-on:click="onTagSelected(selTag)">
                            {{selTag.sign}}
                          </div>
                        </div>
                        <div class="operationView">
                          <div class="confirm" v-on:click="onEditTagFinished(scope.$index)">确定</div>
                          <div class="cancel" v-on:click="onEditTagCanceled(scope.$index)">取消</div>
                        </div>
                      </div>
                      <el-button class="editTagBtn el-icon-caret-bottom" slot="reference"></el-button>
                    </el-popover>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="menu">
        <el-table ref="multipleTable" :data="tagsData" tooltip-effect="dark" style="width: 100%" max-height="845" :highlight-current-row="tagRowHighlight" @header-click="onHeaderClick" @row-click="onTagRowClick">
          <el-table-column label="全部用户">
            <template slot-scope="scope">
              <span>{{scope.row.sign}}</span>
              <span>{{"(" + scope.row.count + ")"}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <pagination v-show="userData.length > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getUserList" />
    <!-- :before-close="closePushSelector" -->
    <el-dialog :close-on-click-modal="false" title="选择标签" :visible.sync="showTagDialog" width="600px" append-to-body>
      <!-- <div>选择标签</div> -->
      <div class="dialogTagsSelector">
        <div :class="{'tag': true, 'selectedTag': selectedTags.indexOf(selTag.sign) >= 0}" v-for="(selTag, selIndex) in tagsData" v-bind:key="selIndex" v-on:click="onTagSelected(selTag)">
          {{selTag.sign}}
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onMoreUserEditTagFinish">确 定</el-button>
        <el-button @click="onMoreUserEditTagCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getUserList,
  updateUserTags,
  getTags,
  addTag,
  deleteTag,
  renameTag,
} from "@/api/reviewActivities/userManager";


export default {
  name: "userManager",
  data() {
    return {
      picturePath: location.hostname == "mgr.shulanfd.com" ?
        "https://api.shulanfd.com/aist-filesvr-web/api/files"
        :
        "https://api-dev.shulanfd.com/aist-filesvr-web/api/files",

      defaultImage: location.hostname == "mgr.shulanfd.com" ?
        'https://api.shulanfd.com/aist-filesvr-web/api/static/jjr/main/moren_touxiang'
        :
        'https://api-test.shulanfd.com/aist-filesvr-web/api/static/jjr/main/moren_touxiang',
      tagState: true, //打标签按钮状态
      blackListState: false, //黑名单按钮状态
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        type: null,
        sign: [],
      },
      showAddTagView: false, // 是否显示添加标签界面
      addTagForm: {
        tagName: null
      },
      userTypes: [], // 用户类型

      showRenamePopover: false, // 是否显示标签重命名界面
      showDeleteTagPopover: false, // 是否显示删除标签提示界面
      showTagDialog: false, // 显示多用户编辑标签界面

      userData: [], // 用户列表数据
      total: 0,  // 用户列表总数
      tagsData: [], // 标签列表数据
      tagValues: {}, // 标签value的数组,用于用户列表根据value获取标签名称
      selectedUsers: [], // 多个用户修改标签选择的用户数组
      selectedTags: [], // 修改标签时选择的标签
      tagRowHighlight: true,
      tagEditEnable: false,
      currentTag: null, // 当前选中的标签信息
    }
  },

  created() {
    this.getUserList();
    this.getTags();
    this.getUserTypes();
  },

  methods: {

    // 重置头部筛选
    resetQuery() {
      this.queryParams.nickName = null;
      this.queryParams.type = null;
      this.queryParams.pageNum = 1;
      this.getUserList();
    },

    // 点击搜索按钮
    onSearchClick() {
      this.queryParams.pageNum = 1;
      this.getUserList();
    },

    //新建标签
    handleCreate() {
      console.log('新建标签')
    },
    //打标签
    handleTag() {
      // 初始化选择的标签数组
      this.selectedTags = [];
      // 显示标签选择界面
      this.showTagDialog = true;
    },

    // 显示标签选择界面
    onShowTagSelector(currentTags) {
      this.selectedTags = currentTags ? [...currentTags] : [];
    },

    // 选择标签
    onTagSelected(tag) {

      if (this.selectedTags.indexOf(tag.sign) >= 0) {
        this.selectedTags.splice(this.selectedTags.indexOf(tag.sign), 1);
      } else {
        this.selectedTags.push(tag.sign);
      }
    },

    // 单个用户编辑标签选择完成
    onEditTagFinished(index) {
      let userInfo = this.userData[index];
      userInfo.showSelector = false;
      if (null == userInfo.sign) {
        if (this.selectedTags.length == 0) return;
      } else {
        if (userInfo.sign.toString() == this.selectedTags.toString()) return;
      }

      // 同步到数据库
      let params = {
        type: "single",
        id: [userInfo.id],
        sign: this.selectedTags
      }
      updateUserTags(params)
        .then(res => {
          console.log("更新用户标签的结果 --->", res);
          userInfo.sign = this.selectedTags;
          // 刷新标签列表
          this.getTags();
        })
    },

    // 单个用户编辑标签选择取消
    onEditTagCanceled(index) {
      this.userData[index].showSelector = false;
    },

    // 多个用户编辑标签完成
    onMoreUserEditTagFinish() {
      this.showTagDialog = false;
      let idArr = [];
      this.selectedUsers.map((user) => {
        idArr.push(user.id);
      })

      let params = {
        type: "more",
        id: idArr,
        sign: this.selectedTags
      }

      updateUserTags(params)
        .then(res => {
          console.log("更新多个用户标签的结果 --->", res);
          this.getUserList();
          this.getTags();
        })
    },

    // 多个用户编辑标签取消
    onMoreUserEditTagCancel() {
      this.showTagDialog = false;
    },


    // 获取用户列表
    getUserList() {
      getUserList(this.queryParams)
        .then(res => {
          console.log("获取用户列表 ---->", res);
          if (res.data.list) {
            this.userData = res.data.list;
          }
          this.total = res.data.total;
          // console.log("头像URL --->", picturePath + "/" + res.data.list[1].avatar)
        })
    },

    getUserTypes() {
      // 获取客户类型
      this.getDicts("user_type").then(response => {
        console.log("客户类型数据字典 --->", response)
        this.userTypes = response.data;
        let tagClasses = ["agentType", "customerType"];
        response.data.map((tag, index) => {
          this.tagValues[tag.dictValue] = {
            name: tag.dictLabel,
            privateStyle: index >= tagClasses.length ? tagClasses[0] : tagClasses[index],
          }
        })
      });
    },

    // 获取所有标签数据
    getTags() {
      getTags()
        .then(res => {
          console.log("用户标签数据 --->", res);
          this.tagsData = res.data;
        })
    },

    // 确认添加标签
    onConfirmAddTag() {
      if (null == this.addTagForm.tagName || this.addTagForm.tagName == '') return;
      let params = {
        sign: this.addTagForm.tagName
      }
      addTag(params)
        .then(res => {
          console.log("添加标签结果 ---->", res);
          if (res.data) this.tagsData.push(res.data);

        })
      this.showAddTagView = false;
    },

    // 取消添加标签
    onCancelAddTag() {
      this.showAddTagView = false;
    },

    // 确定重命名标签
    onConfirmRenameTag() {
      if (null == this.addTagForm.tagName || this.addTagForm.tagName == '') return;
      let params = {
        id: this.currentTag.id,
        sign: this.addTagForm.tagName
      }
      renameTag(params)
        .then(res => {
          console.log("重命名标签的结果 ----->", res);
          this.getTags();
          this.getUserList();
        })
      this.showRenamePopover = false;
    },

    // 取消重命名标签
    onCancelRenameTag() {
      this.showRenamePopover = false;
    },

    // 新建标签/重命名标签界面关闭时, 初始化数据
    onTagPopoverHide() {
      this.addTagForm.tagName = null;
    },

    // 确定删除标签
    onConfirmDeleteTag() {
      let params = {
        id: this.currentTag.id
      };
      deleteTag(params)
        .then(res => {
          console.log("删除标签的结果 --->", res);
          if (res.code === 200) {
            this.queryParams.sign = [];
            this.getTags();
            this.getUserList();
          }
        })
      this.showDeleteTagPopover = false;
    },

    // 取消删除标签
    onCancelDeleteTag() {
      this.showDeleteTagPopover = false;
    },

    // 点击标签列表头部查看全部用户
    onHeaderClick() {
      // 不能进行标签的重命名和删除操作
      this.tagEditEnable = false;
      // 取消表格高亮
      this.tagRowHighlight = false;

      this.queryParams.sign = [];
      this.getUserList();
    },

    // 点击标签筛选用户列表
    onTagRowClick(row, column, event) {
      // 可以进行标签的重命名和删除操作
      this.tagEditEnable = true;
      // 开启表格高亮效果
      this.tagRowHighlight = true;
      // 存储当前选择的标签信息,用于重命名和删除操作
      this.currentTag = row;

      this.queryParams.sign = [row.sign];
      this.getUserList();
    },

    // 选择单个用户
    onUserSelected(selection, row) {
      console.log("选择了单个用户 --->", selection)
      this.selectedUsers = selection
    },

    // 全选用户
    onUserSelectedAll(selection) {
      console.log("选择了全部用户 --->", selection)
      this.selectedUsers = selection
    },
  }

}
</script>

<style lang="scss" scoped>
.header-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content {
  display: flex;
  width: 100%;

  .userList {
    width: 80%;
    border: #ddd 1px solid;
    border-bottom: 0px;

    .listTitle {
      padding-top: 12.5px;
      padding-bottom: 12.5px;
      padding-left: 10px;
      border-bottom: #ddd 1px solid;
    }

    .check-all {
      position: relative;
    }

    .check-all:before {
      content: "全选";
      position: absolute;
      left: 30px;
      width: 40px;
      top: 17px;
    }

    .userItem {
      height: 60px;
      display: flex;
      align-items: center;

      .userItemImg {
        height: 50px;
        width: 50px;
        margin-right: 15px;
      }

      .username {
        display: flex;
        align-items: center;
        margin-bottom: 5px;

        .userTypeTag {
          display: flex;
          justify-content: center;
          align-items: center;
          color: white;
          font-size: 11px;
          height: 17px;
          min-width: 40px;
          padding-left: 5px;
          padding-right: 5px;
          border-radius: 2px;
          margin-left: 5px;
        }

        .agentType {
          background-color: rgba(65, 145, 250, 1);
        }

        .customerType {
          background-color: rgba(95, 200, 112, 1);
        }
      }

      .tagsView {
        display: flex;
      }

      .editTagBtn {
        padding: 1px;
        border: 0px;
      }
    }
  }

  .menu {
    width: 20%;
    max-width: 200px;
    min-width: 150px;
    border: #ddd 1px solid;
    border-left: 0px;
  }
}

.tagsSelector {
  display: flex;
  flex-wrap: wrap;
  max-width: 400px;
  padding-top: 5px;
  padding-bottom: 5px;

  .tag {
    margin-top: 5px;
    margin-bottom: 5px;
  }
}

.dialogTagsSelector {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  padding-top: 5px;
  padding-bottom: 5px;
  margin-top: 10px;

  .tag {
    margin-top: 5px;
    margin-bottom: 5px;
  }
}

.operationView {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;

  div {
    background-color: rgba(65, 145, 250, 1);
  }

  .confirm {
    height: 30px;
    width: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    margin-right: 15px;
    color: white;
  }

  .cancel {
    height: 30px;
    width: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    background-color: #eee;
  }
}

.tag {
  display: flex;
  align-items: center;
  height: 22px;
  color: #999;
  padding-left: 9px;
  padding-right: 9px;
  border: #999 1px solid;
  border-radius: 11px;
  margin-right: 10px;
}

.selectedTag {
  border-color: rgba(65, 145, 250, 1);
  color: rgba(65, 145, 250, 1);
}

.addTagTitle {
  margin-bottom: 10px;
}

.addTagOperation {
  margin-top: 15px;
}

.deleteHint {
  width: 240px;
}

.deleteTagOperation {
  margin-top: 30px;
}

.deleteTagPopover {
  margin-left: 10px;
}
</style>
